package captcha

import (
	"github.com/mojocn/base64Captcha"
	"image/color"
	"sync"
)

type CaptchaConfig struct {
	Id             string
	DriverAudio    base64Captcha.DriverAudio
	DriverString   base64Captcha.DriverString
	DriverDigit    base64Captcha.DriverDigit
	DriverChinese  base64Captcha.DriverChinese
	DriverLanguage base64Captcha.DriverLanguage
	DriverMath     base64Captcha.DriverMath
}

var (
	captchaConfig     *CaptchaConfig
	captchaConfigOnce sync.Once
)

// 获取base64验证码基本配置
func GetCaptchaConfig() *CaptchaConfig {
	captchaConfig = &CaptchaConfig{
		Id: "",
		DriverString: base64Captcha.DriverString{
			Height:          40,                                                                     //高度
			Width:           133,                                                                    //宽度
			NoiseCount:      0,                                                                      //干扰数
			ShowLineOptions: base64Captcha.OptionShowHollowLine | base64Captcha.OptionShowSlimeLine, //展示个数
			Length:          4,                                                                      //长度
			Source:          base64Captcha.TxtNumbers + base64Captcha.TxtAlphabet,                   //验证码随机字符串来源
			BgColor: &color.RGBA{ // 背景颜色
				R: 3,
				G: 102,
				B: 214,
				A: 125,
			},
			Fonts: []string{"wqy-microhei.ttc"}, // 字体
		},
	}
	return captchaConfig
}

// 获取验证码
func MakeStringCaptcha(store base64Captcha.Store) (string, string, error) {
	//定义一个driver
	var driver base64Captcha.Driver
	config := GetCaptchaConfig()
	//创建一个字符串类型的验证码驱动DriverString, DriverChinese :中文驱动
	driver = config.DriverString.ConvertFonts()
	//生成验证码
	c := base64Captcha.NewCaptcha(driver, store)
	id, b64s, err := c.Generate()
	return id, b64s, err
}

// 校验验证码
func VerifyCaptcha(store base64Captcha.Store, id string, VerifyValue string) bool {
	// 参数说明: id 验证码id, verifyValue 验证码的值, true: 验证成功后是否删除原来的验证码
	if store.Verify(id, VerifyValue, true) {
		return true
	} else {
		return false
	}
}
